package monitor;

import java.io.IOException;
import java.util.Collection;

import operacoes.GridMonitorOperation;
import operacoes.Mensagem;
import cliente.ClientSocket;

public class Heartbeat extends Thread{

	public void run(){
		Collection<Host> hosts;
	    while(true){
			boolean existe = Tabelas.existeMonitorados();
			while(existe){
				hosts = Tabelas.getHostsConhecidos();
				if((hosts != null) && (hosts.size() > 0 )){  //While the host's table is not empty
					for (Host host : hosts) {
						try{
							ClientSocket.enviarMSG(host.getIp(), host.getPorta(), Mensagem.montarMensagem(TipoOperacao.HEARTBEAT+""));
						}catch(IOException e){
							System.out.println("Heartbeat: " + e.getMessage());
							GridMonitorOperation.failureDetected(host.getIp(), host.getPorta());
							break; 
						}catch(Exception e){
							System.out.println("Heartbeat: " + e.getMessage());
							GridMonitorOperation.failureDetected(host.getIp(), host.getPorta());
							break;
						} finally{
							try {
								Thread.sleep(30000);
							} catch (InterruptedException e) {
								System.out.println("Heartbeat: " + e.getMessage());
							}							
						}
					}
				}
				existe = Tabelas.existeMonitorados();
			}
			try {
				Thread.sleep(30000);
			} catch (InterruptedException e) {
				System.out.println("Heartbeat: " + e.getMessage());
			}
		}
	}
}
